package cn.lili.modules.lucene;

import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;

/**
 * @Author Sylow
 * @Description 索引工厂
 * @Date: Created in 15:41 2025/6/23
 */
@Slf4j
@Component
public class IndexWriterFactory {
    private final Directory directory;
    private final Analyzer analyzer = new IKAnalyzer(true);

    @Autowired
    public IndexWriterFactory(Directory directory) {
        this.directory = directory;
    }

    public IndexWriter createWriter() throws IOException {
        // 每次创建新的配置实例解决 IllegalStateException
        IndexWriterConfig config = createNewConfig();
        return new IndexWriter(directory, config);
    }

    private IndexWriterConfig createNewConfig() {
        IndexWriterConfig config = new IndexWriterConfig(analyzer);
        config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
        config.setRAMBufferSizeMB(256);
        config.setUseCompoundFile(false);
        return config;
    }
}

